<template>
  <div>
    <ShareCard
      :loading="isLoading"
      :cardData="cardData"
      :showTitle="showTitle"
      :bodyStyle="{ padding: '0 20px 20px' }"
    >
      <Tabs v-model:activeKey="activeKey">
        <TabPane :key="index" v-for="(item, index) in handle_list">
          <template #tab>
            <div @mouseenter="onMousemove(item, index)" @click="onTabClick(item)">{{
              item.tabName
            }}</div>
          </template>
        </TabPane>
      </Tabs>
      <BasicTable
        @register="registerTable"
        :pagination="pagination"
        :class="{ cus_table: !isTable }"
        @resize-column="handleResizeColumn"
        :customHeaderRow="customHeader"
      />
      <ProcessDrawer
        @register="registerDrawer"
        @success="handleSuccess"
        @launch-flow-action="handleLaunchFlowInDrawer"
      />
      <ProcessShowDrawer @register="registerViewDrawer" @handle-current="handleProcess" />
    </ShareCard>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, h, nextTick } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import ShareCard from './ShareCard.vue';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { Tabs, TabPane, Tag } from 'ant-design-vue';
  import { getFlowList, getFlowListPage, getFlowInit } from '/@/api/process/process';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDebounceFn } from '@vueuse/core';
  import { colorList } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/nodeEdit/nodeEdit.data';
  import ProcessDrawer from '/@/views/pages/processManagement/processDrawer.vue';
  import ProcessShowDrawer from '/@/views/pages/processManagement/processShowDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  const props = defineProps({
    loading: Boolean,
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '300px',
    },
    icon: {
      type: String as PropType<string>,
      default: '',
    },
    pageSize: {
      type: Number,
      default: 6,
    },
    pagination: {
      type: Boolean,
      default: true,
    },
    cardData: {
      type: Object as PropType<object>,
      default: () => {
        return {};
      },
    },
    showTitle: {
      type: Boolean,
      default: true,
    },
  });
  const { createMessage } = useMessage();
  const activeKey = ref(0);
  const isLoading = ref(false);
  const handle_list = ref<Recordable[]>([]);
  const currentTabRecord = ref<Recordable>({});
  const cardDataObj = ref<Recordable>({});
  const listPage = ref<Recordable>({});
  const isTable = ref(false);
  let flowColumns: BasicColumn[] = [];
  let flowOpStyle = 0;
  const fetch = () => {
    console.log('cardData', props.cardData);
    cardDataObj.value = props.cardData;
    if (cardDataObj.value?.meta?.handle_list && isArray(cardDataObj.value?.meta?.handle_list)) {
      //过滤可用的
      handle_list.value = cardDataObj.value.meta.handle_list.filter((item) => item.isUse);
      if (handle_list.value.length) {
        currentTabRecord.value = handle_list.value[0];
        searchData();
      }
    }
  };

  const [registerTable, { reload, setPagination, setColumns }] = useTable({
    title: '',
    api: getFlowList,
    columns: [],
    formConfig: {
      //   schemas: [],
    },
    searchInfo: {
      op: 'search',
    }, //额外的参数
    useSearchForm: false,
    showTableSetting: false,
    bordered: unref(isTable),
    indexColumnProps: { width: 50 },
    showIndexColumn: false,
    immediate: false,
    canResize: false,
    striped: unref(isTable), //斑马纹
    beforeFetch: (info) => {
      let newInfo = info;
      if (!props.pagination) {
        newInfo.pageSize = props.pageSize;
      }
      newInfo.type = unref(currentTabRecord).type;
      newInfo.typeCode = unref(currentTabRecord).code;
      return newInfo;
    },
    rowKey: 'id',
    // rowSelection: {
    //   type: 'checkbox',
    // },
    // actionColumn: {
    //   width: 120,
    //   title: '操作',
    //   dataIndex: 'action',
    //   slots: { customRender: 'action' },
    //   fixed: 'right',
    // },
  });
  const handleResizeColumn = (w, col) => {
    col.width = w;
  };

  const getListPage = async () => {
    await getFlowListPage({
      type: unref(currentTabRecord).type,
      typeCode: unref(currentTabRecord).code,
    }).then(async (res) => {
      if (res.code == 500) {
        createMessage.warn(res.msg);
        return;
      }

      listPage.value = res.data;
      flowColumns = [];
      if (listPage.value['colProps'] && listPage.value['colProps'].length > 0) {
        const data = listPage.value['colProps']
          .filter((item) => item['field'] != 'f.id' && item['field'] != 'f.flow_level')
          .slice(0, 5);
        data.forEach((item) => {
          if (item.field == 'f.status') {
            flowColumns.push({
              title: item.title ? item.title : item.display,
              dataIndex: item.field ? item.field : item.name,
              align: item.align || 'center',
              // fixed: item.fixed,
              width: item.width,
              sorter: unref(isTable) ? item.sort : unref(isTable),
              ellipsis: true,
              resizable: unref(isTable),
              customRender: ({ record: { statusRaw, 'f.status': status } }) => {
                // 解构
                // let { statusRaw, 'f.status': status } = record;
                let colors: string[];
                // 如果为待办流程
                if (currentTabRecord.value.type == 'doing') {
                  colors = [
                    'blue',
                    '#cccccc',
                    'orange',
                    '#f50',
                    'green',
                    'pink',
                    'red',
                    '#2db7f5',
                    'pink',
                    'cyan',
                  ];
                } else {
                  colors = ['blue', 'orange', 'green', 'red', '#f50'];
                }

                return h(Tag, { color: colors[statusRaw] }, () => status || '结束');
              },
            });
          } else if (item.field == 'f.title') {
            flowColumns.push({
              title: item.title ? item.title : item.display,
              dataIndex: item.field ? item.field : item.name,
              align: 'left',
              // fixed: item.fixed,
              width: item.width,
              sorter: unref(isTable) ? item.sort : unref(isTable),
              ellipsis: true,
              resizable: unref(isTable),
              customRender: ({ text, record }) => {
                return h(
                  'div',
                  {
                    onClick: () => handleTileClcik(record),
                    title: text,
                    class:
                      'cursor-pointer ' +
                      (currentTabRecord.value.type == 'doing' &&
                      record.hasOwnProperty('isReaded') &&
                      !record.isReaded
                        ? 'font-bold'
                        : ''),
                  },
                  text,
                );
              },
            });
          } else if (item.field == 'f.currentAction') {
            flowColumns.push({
              title: item.title ? item.title : item.display,
              dataIndex: item.field ? item.field : item.name,
              align: item.align || 'center',
              // fixed: item.fixed,
              width: item.width,
              sorter: unref(isTable) ? item.sort : unref(isTable),
              ellipsis: true,
              resizable: unref(isTable),
              customRender: ({ record, text }) => {
                const curColorRecord = colorList.find(
                  (item) => item.id == record.currentActionColorIndex,
                );
                if (curColorRecord) {
                  return h(Tag, { color: curColorRecord.color }, () => text || '--');
                }
                return h(Tag, () => text || '--');
              },
            });
          } else {
            flowColumns.push({
              title: item.title ? item.title : item.display,
              dataIndex: item.field ? item.field : item.name,
              align: item.align || 'center',
              // fixed: item.fixed,
              width: item.width,
              sorter: unref(isTable) ? item.sort : unref(isTable),
              ellipsis: true,
              resizable: unref(isTable),
              slots: {
                customRender: item.field == 'f.title' ? 'title' : item.field,
              },
            });
          }
        });
      }
      setColumns(flowColumns);
      serach();
    });
  };
  const serach = () => {
    setPagination({
      pageSize: props.pageSize,
      current: 1,
    });
    reload();

    //获取 flowOpStyle
    getFlowList({
      pageSize: 1,
      type: unref(currentTabRecord).type,
      typeCode: unref(currentTabRecord).code,
    }).then((res) => {
      flowOpStyle = res.flowOpStyle;
    });
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerViewDrawer, { openDrawer: openViewDrawer, closeDrawer: closeViewDrawer }] =
    useDrawer();

  //页面回调
  function handleSuccess() {
    searchData();
  }
  const go = useGo();
  //标题点击
  const handleTileClcik = (record) => {
    handleEdit(record);
  };

  function handleEdit(record: any) {
    console.log('currentTabRecord.value', currentTabRecord.value);
    const type = currentTabRecord.value.type;
    if (type == 'attend' || type == 'urge') {
      if (flowOpStyle == 1) {
        let title = record['f.id'] + '-' + record['f.title'];
        if (title.length > 18) {
          title = title.substring(0, 18) + '...';
        }
        go({
          path: '/processShow',
          query: {
            flowId: record['f.id'],
            title: title,
            isFromProcess: true,
            cacheName: `processShow${record['f.id']}`,
          },
        });
      } else {
        openViewDrawer(true, {
          flowId: record['f.id'],
        });
      }
    } else {
      if (flowOpStyle == 1) {
        let title = record['f.id'] + '-' + record['f.title'];
        if (title.length > 18) {
          title = title.substring(0, 18) + '...';
        }
        if (record.type == 2) {
          go({
            path: '/processHandle',
            query: {
              myActionId: record.id,
              isFromProcess: true,
              title: title,
              cacheName: `processHandle${record['f.id']}`,
            },
          });
        } else {
          go({
            path: '/processHandleFree',
            query: {
              myActionId: record.id,
              isFromProcess: true,
              title: title,
              cacheName: `processHandle${record['f.id']}`,
            },
          });
        }
      } else {
        openDrawer(true, {
          myActionId: record.id,
          type: record.type,
        });
      }
    }
  }

  const handleProcess = (record) => {
    closeViewDrawer();

    if (flowOpStyle == 1) {
      let title = record['f.id'] + '-' + record['f.title'];
      if (title.length > 18) {
        title = title.substring(0, 18) + '...';
      }
      if (record.type == 2) {
        go({
          path: '/processHandle',
          query: {
            myActionId: record.id,
            isFromProcess: true,
            title: title,
            cacheName: `processHandle${record['f.id']}`,
          },
        });
      } else {
        go({
          path: '/processHandleFree',
          query: {
            myActionId: record.id,
            isFromProcess: true,
            title: title,
            cacheName: `processHandle${record['f.id']}`,
          },
        });
      }
    } else {
      openDrawer(true, {
        myActionId: record.id,
        type: record.type,
      });
    }
  };

  const searchData = () => {
    getListPage();
  };

  // 防抖，延迟500ms执行
  const debounceFresh = useDebounceFn(searchData, 500);
  //鼠标移动事件
  const onMousemove = (item: any, index) => {
    //如果值一样不执行
    if (activeKey.value === index) return;
    currentTabRecord.value = item;
    activeKey.value = index;
    debounceFresh();
  };

  //点击tab去哪
  const onTabClick = ({ type, code, tabName }) => {
    switch (type) {
      case 'doing':
        go({
          path: '/flow/doing',
          query: {
            typeCode: code,
            tabName,
          },
        });
        break;
      case 'read':
        go({
          path: '/flow/read',
          query: {
            typeCode: code,
            tabName,
          },
        });
        break;
      case 'attend':
        go({
          path: '/flow/attend',
          query: {
            typeCode: code,
            tabName,
          },
        });
        break;
      case 'urge':
        go({
          path: '/flow/urge',
          query: {
            typeCode: code,
            tabName,
          },
        });
        break;
      default:
        break;
    }
  };

  onMounted(fetch);

  const customHeader = (column) => {
    console.log('customHeader column', column);
    column.forEach((e, index) => {
      column[index].className = 'boldFont';
      // column[index]['customRender'] = ({ text, record }) => {
      //   // return h('span', {
      //   //   value: text + '1',
      //   //   style: 'font-weight: 700; color: red',
      //   // });
      //   console.log('text', text);
      //   return h('span', { fontWeight: 700 }, text + '1');
      // };
    });

    return {
      props: {
        // draggable: 'true'
      },
      style: {
        fontWeight: 700,
      },
    };
  };

  // 在处理流程页面或编辑或查看详情抽屉中发起流程
  function handleLaunchFlowInDrawer(item) {
    // 发起流程
    let params = {
      op: 'opBtnFlow',
      typeCode: item.flowTypeCode,
      ...item,
    };
    getFlowInit(params).then((res) => {
      let myActionId = res.myActionId || '';
      if (myActionId) {
        openDrawer(true, {
          myActionId: myActionId,
          type: res.type,
        });
      }
    });
  }
</script>
<style lang="less" scoped>
  :deep(.boldFont) {
    font-weight: 700;
  }
  :deep(.ant-table-thead > tr > th) {
    font-weight: 700 !important;
  }
  :deep(.m-2) {
    margin: 0 !important;
  }
  :deep(.ant-card-head) {
    min-height: 0;
    height: 0;
  }
  .cus_table {
    :deep(.ant-table-thead > tr > th) {
      background-color: transparent;
    }
  }

  :deep(.ant-table-thead
      > tr
      > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
    background-color: transparent;
  }
  :deep(.ant-tabs-top > .ant-tabs-nav, .ant-tabs-bottom > .ant-tabs-nav, .ant-tabs-top
      > div
      > .ant-tabs-nav, .ant-tabs-bottom > div > .ant-tabs-nav) {
    margin: 0;
  }
</style>
